package com.czf.netty.czf20220708;

import com.czf.netty.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author zfChen
 * @create 2022/7/8 14:23
 */
public class TestCodec {
    public static void main(String[] args) throws Exception {

        LoggingHandler loggingHandler = new LoggingHandler();
        LengthFieldBasedFrameDecoder lengthFieldBasedFrameDecoder = new LengthFieldBasedFrameDecoder(
                1024, 12, 4, 0, 0);
        EmbeddedChannel channel = new EmbeddedChannel(
                lengthFieldBasedFrameDecoder,
                loggingHandler,
                new MessageCodec()
        );
        // encode
        LoginRequestMessage message = new LoginRequestMessage("zhang", "123");
        // 出站   出站是编码
        channel.writeOutbound(message);
        // decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, message, buf);
        // 入站   入站是解码
        channel.writeInbound(buf);
//
//        ByteBuf s1 = buf.slice(0, 100);
//        ByteBuf s2 = buf.slice(100, buf.readableBytes() - 100);
//        s1.retain(); // 由于入站后buf会被释放，所以需要加引用。引用计数 2
//        channel.writeInbound(s1); // release 1
//        channel.writeInbound(s2);
    }
}
